import { loadMicroApp } from 'qiankun'
import pluginData from './pluginData.js'
import './envMarkPatch.js' // 环境标识补丁
import './projectCommonConfig' // 项目统一配置
let baseUrl = '';
let loadedPlugins = {}; // 已加载过的插件


const setBaseUrl = (PLUGIN_ENV) => {
  let origin = window.location.origin;
  if (origin.indexOf('localhost') !== -1 || origin.indexOf('http://192.168') !== -1) { // 本地
    if (PLUGIN_ENV === 'dev') {
      return baseUrl = 'http://139.9.35.40'
    } else if (PLUGIN_ENV === 'test') {
      return baseUrl = 'http://139.9.35.40'
    }
  }
  return baseUrl = ''; // 不是本地
}

/**
 * 获取插件对应版本的loadUrl
 * @param pluginName
 * @param pluginConfig
 * @param pluginVersion
 * @returns {string|*}
 */
function getLoadUrl(pluginName, pluginConfig, pluginVersion) {
  if(!pluginVersion) {
    return pluginConfig.loadUrl;
  }else {
    if(pluginConfig.otherVersion && pluginConfig.otherVersion[pluginVersion] && pluginConfig.otherVersion[pluginVersion].loadUrl) {
      return pluginConfig.otherVersion[pluginVersion].loadUrl;
    } else {
      throw Error('未找到插件' + pluginName +'的' + pluginVersion + '版本loadUrl');
    }
  }
}

/**
 *加载单个插件
 * @param pluginName
 * @param pluginConfig
 * @param pluginVersion
 * @returns {Promise<any>}
 */
function loadScript(pluginName, pluginConfig, pluginVersion){
  if(!loadedPlugins[pluginName]) {
    let scriptPromise = new Promise((resolve,reject)=> {
      let script = document.createElement('script');
      let head = document.getElementsByTagName('head')[0];
      script.type = 'text/javascript';
      script.src = baseUrl + getLoadUrl(pluginName, pluginConfig, pluginVersion);
      if (script.addEventListener) {
        script.addEventListener('load', function () {
          resolve();
        }, false);
        script.addEventListener('error', function () {
          reject();
        }, false);
      } else if (script.attachEvent) {
        script.attachEvent('onreadystatechange', function () {
          var target = window.event.srcElement;
          if (target.readyState === 'loaded') {
            resolve();
          } else {
            reject();
          }
        });
      }
      head.appendChild(script);
      //将该插件插入loadedPlugins中
    });
    loadedPlugins[pluginName] = {
      version:pluginVersion,
      scriptPromise
    };
    return scriptPromise
  } else {
    if(loadedPlugins[pluginName].version === pluginVersion) {
      return loadedPlugins[pluginName].scriptPromise;
    }else {
      throw Error('已调用' + pluginName + '插件的其他版本');
    }
  }
}

/**
 * 加载插件集合
 * @param pluginArr
 * @returns {Promise<any[]>}
 */
let loadPlugins = function (pluginArr, PLUGIN_ENV = 'dev') {
  setBaseUrl(PLUGIN_ENV) // 设置插件加载环境地址
  let loadScriptArr = [];
  if(Object.prototype.toString.call(pluginArr) !== "[object Array]") {
    throw Error('loadPlugins函数需要传入数组类型的参数')
  }
  for(let i=0; i<pluginArr.length; i++) {
    let currentPlugin,pluginVersion;
     // 需要区分版本号的插件
    if(!pluginArr[i].includes('|')) {
      currentPlugin = pluginArr[i];
    } else {
      let temp = pluginArr[i].split('|');
      currentPlugin = temp[0];
      pluginVersion = temp[1];
    }
    // 若插件自身有依赖
    if(pluginData[currentPlugin] && pluginData[currentPlugin].dependence && pluginData[currentPlugin].dependence.length) {
      loadScriptArr.push(loadPlugins(pluginData[currentPlugin].dependence, PLUGIN_ENV).then(() => {
          return loadScript(currentPlugin, pluginData[currentPlugin],pluginVersion);
      }));
    } else if(pluginData[currentPlugin]) {
      loadScriptArr.push(loadScript(currentPlugin, pluginData[currentPlugin],pluginVersion));
    } else {
      throw Error(currentPlugin + '插件未注册');
    }
  }
  return Promise.all(loadScriptArr);
};

function loadYxpMicroApp(options) {
  return new Promise((resolve, reject) => {
    let currentMicroApp = pluginData[options.name];
    let loadMicroAppByQK = function (options) {
      return loadMicroApp(Object.assign(options,{
        entry: (options.NODE_ENV === 'development' && options.entry) ? options.entry : baseUrl + currentMicroApp.loadUrl,
      }));
    }
    if(currentMicroApp && currentMicroApp.type === 'microApp') {
      // 先加载微应用的依耐
      if(currentMicroApp.dependence && currentMicroApp.dependence.length) {
        loadPlugins(currentMicroApp.dependence).then(res => {
          resolve(loadMicroAppByQK(options))
        })
      } else {
        resolve(loadMicroAppByQK(options))
      }

    } else {
      reject(options.name + '微服务未注册');
    }
  })
}
window.loadPlugins = loadPlugins;
Object.assign(window,{
  loadPlugins,
  loadYxpMicroApp
})

export default {
  loadPlugins,
  pluginData,
  loadYxpMicroApp
}
